// skynet spulletjes
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
#include "alg.h"
#include "imdb.h"
#include "cache.h"

extern pthread_mutex_t mymutex;
// Teller connecties
extern int maxconn;
extern int mconnect;
//
// //--quiet
extern int stil;
// // (default)aantal dagen om te grabben: --days
extern int days;
// // --offset
extern int offset;
// // --cache
extern short cache;
extern FILE *cachefp;
extern FILE *cachetmp;
extern short imdb;
extern short imdbdirty;
extern int aantalimdb;
// TimeZone
extern short tz;		// Nederland = +0100 (wintertijd, zomertijd = +0200)
//tellertjes
extern unsigned long aantalprog;
extern unsigned long aantalcache;
// systeem jaar, maand, dag.
extern int sys_jaar;
extern int sys_maand;
extern int sys_dag;
extern int sys_wdag;
int maxconn_sky = 0;

//online channels voor config van skynet halen, return 0 NOT OK.
short getchan_skynet(void)
{
	extern channel channelsconf2[];
	CURL *handle;
	char curlerror[CURL_ERROR_SIZE];
	char buffer[1024];
	char url[512];
	int tmpptr, tel = 0, tel2;
	char *p1, *p2;
	FILE *tempfile;
	char template[] = "/tmp/chan_XXXXXX";
	int aantalpag = 0;
	if (!(handle = curl_easy_init()))
		return (0);
	tmpptr = mkstemp(template);
	if (tmpptr == -1)
		return (0);
	tempfile = fdopen(tmpptr, "w+");
	if (tempfile == NULL)
		return (0);
	curl_easy_setopt(handle, CURLOPT_URL,
			 //"http://tv-nl.skynet.be/blank.html?l1=actuality&l2=tvguide&l3=accroche&l4=channels_selectionbox&channelid=7&channel_pagenb=1");
			 "http://www.skynet.be/entertainment-nl/tv/kanalen_vtm");
	curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(handle, CURLOPT_AUTOREFERER, 1);
	curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 5);
	curl_easy_setopt(handle, CURLOPT_WRITEDATA, tempfile);
	curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, curlerror);
	curl_easy_setopt(handle, CURLOPT_TIMEOUT, TIMEOUT);
	//curl_easy_setopt(handle, CURLOPT_VERBOSE, 1);

	fprintf(stderr,
		"Ophalen zenders van tv-nl.skynet.be, momentje a.u.b.\n");
	if (curl_easy_perform(handle)) {
		fprintf(stderr, "Error online channelconfig: '%s'\n",
			curlerror);
		curl_easy_cleanup(handle);
		fclose(tempfile);
		unlink(template);
		return (0);
	}
	//curl_easy_cleanup(handle);
	rewind(tempfile);
	while (fgets(buffer, 1024, tempfile)) {
		//lijst van channels op pagina zoeken
		if (strstr(buffer, "<div id=\"channelBox\">")) {
			while (fgets(buffer, 1024, tempfile)) {
				if (strstr(buffer, "</ul>"))	//einde lijst
					break;
				//zendertitel pakken
				p2 = strstr(buffer, "title=\"");
				if (p2 == NULL)
					continue;
				p1 = strchr(p2, '"');
				if (p1 == NULL)
					continue;
				p1++;
				p2 = strchr(p1, '"');
				*p2 = '\0';
				channelsconf2[tel].omschrijving =
				    strdup(p1);
				conv_char(channelsconf2[tel].omschrijving);

				//zenderid pakken
				p2 = strstr(buffer, "channelid=");
				if (p2 == NULL)
					continue;
				p1 = strchr(p2, '=');
				if (p1 == NULL)
					continue;
				p1++;
				p2 = strchr(p1, '"');
				*p2 = '\0';
				channelsconf2[tel].id = strdup(p1);
				//strcpy(channelsconf2[tel].id, p1);
				channelsconf2[tel].provider = 3;
				channelsconf2[tel].icon = NULL;
				conv_char(channelsconf2[tel].id);
				tel++;
			}

		}
		if (tel)
			break;
	}
	//rewind(tempfile);
/*
	while (fgets(buffer, 1024, tempfile)) {
        //fprintf(stderr, "aantalpag %d\n", aantalpag);
        if( p2 = strstr(buffer, "<p><strong>1") ) {
            p1 = strchr(p2, '/');
            if(p1 == NULL )
                continue;
            p1++;
            p2 = strchr(p1, '<');
            if(p2 == NULL )
                continue;
		    *p2 = '\0';
            aantalpag = atoi(p1);
            //fprintf(stderr, "aantalpag %d\n", aantalpag);
            break;
        }
    }
*/
/*
	rewind(tempfile);
    for(tel2=2;tel2 <= aantalpag ;tel2++) {
			 sprintf(url, "http://tv-nl.skynet.be/blank.html?l1=actuality&l2=tvguide&l3=accroche&l4=channels_selectionbox&channelid=7&channel_pagenb=%d", tel2);
    //        fprintf(stderr, "url %s\n", url);
	    curl_easy_setopt(handle, CURLOPT_URL, url);
	    if (curl_easy_perform(handle)) {
	    	fprintf(stderr, "Error online channelconfig skynet: '%s'\n",
	    		curlerror);
	        curl_easy_cleanup(handle);
	    	fclose(tempfile);
	    	unlink(template);
	    	return (0);
	    }
    }
*/
/*
	rewind(tempfile);
	while (fgets(buffer, 1024, tempfile)) {
    //lijst van channels op pagina zoeken
	  if (strstr(buffer, "<ul name=\"channel_id\">")) {
		while (fgets(buffer, 1024, tempfile)) {
            if(strstr(buffer, "</ul>")) //einde lijst
                break;
                 //zendertitel pakken
    //             fprintf(stderr, "buff %s\n", buffer);
	    	p2 = strstr(buffer, "title=\"");
	    		if (p2 == NULL)
	    			continue;
                p1 = strchr(p2, '"');
	    		if (p1 == NULL)
	    			continue;
                p1++;
				p2 = strchr(p1, '"');
				*p2 = '\0';
				channelsconf2[tel].omschrijving = strdup(p1);
				conv_char(channelsconf2[tel].omschrijving);

                //zenderid pakken
				p2 = strstr(buffer, "channelid=");
				if (p2 == NULL)
				   continue;
                p1 = strchr(p2, '=');
				if (p1 == NULL)
				    continue;
                p1++;
				p2 = strchr(p1, '&');
				*p2 = '\0';
				channelsconf2[tel].id = strdup(p1);
				 //strcpy(channelsconf2[tel].id, p1);
				channelsconf2[tel].provider = 3;
				channelsconf2[tel].icon = NULL;
				conv_char(channelsconf2[tel].id);
				tel++;
	        }
        }
    }
*/
	if (tel > 0) {
		channelsconf2[tel].id = NULL;
		channelsconf2[tel].omschrijving = "";
	}
	curl_easy_cleanup(handle);
	fprintf(stderr, "%d zenders gevonden.\n", tel);
	fclose(tempfile);
	//unlink(template);
	fprintf(stderr, "template:'%s'\n", template);
	return (1);
}

//data ophalen / verwerken skynet
int skynet(channel * kanaal)
{
	CURL *tvshandle;
	char curlerror[CURL_ERROR_SIZE];
	char url[500];
//////  //long curly;
	int ret;
	int tel = 0;
	int tel2 = 0;
	int tmpptr;
	FILE *tempfile;
	char template[21];
	char buffer[1024];
	char *p, *p1;
	char startdatum[9];
	char starttijd[15];
	char stoptijd[15];
	short dagtel = 0;	//0 en 1 is today/tomorrow
	long position;
	char datjaar[5];
	datjaar[4] = '\0';
	char datmaand[3];
	datmaand[2] = '\0';
	char datdag[3];
	datdag[2] = '\0';
	short avond;
	int groot;
	struct programma {
		char *id;
		char *titel;
		char *startuur;
		char *startmin;
		char *stopuur;
		char *stopmin;
		char *progdatum;
		char *details;
	};
	struct programma ids[4000];
	static char *presentator[20];
	static char *regie[20];
	static char *actors[20];
	short credits = 0;
	char *genre = NULL;
	char jaarpremiere[5];
	jaarpremiere[0] = '\0';
	char stars[10];
	stars[0] = '\0';
	short videoaspect = 0;

	if (!(tvshandle = curl_easy_init())) {
		fprintf(stderr, "Unable to open curl easy tvshandle");
		return (3);
	}
	sprintf(template, "/tmp/%s.grab_XXXXXX", kanaal->id);
	tmpptr = mkstemp(template);
	if (tmpptr == -1)
		return (0);
	if (!(tempfile = fdopen(tmpptr, "w+"))) {
		fprintf(stderr, "ERROR openen tmpfile '%s' bij %s :",
			template, kanaal->id);
		perror("create tempfile skynet");
		return (0);
	}

	curl_easy_setopt(tvshandle, CURLOPT_NOSIGNAL, 1);
//      curl_easy_setopt(tvghandle, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(tvshandle, CURLOPT_AUTOREFERER, 1);
	curl_easy_setopt(tvshandle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(tvshandle, CURLOPT_MAXREDIRS, 5);
	curl_easy_setopt(tvshandle, CURLOPT_WRITEDATA, tempfile);
//////  //curl_easy_setopt(tvghandle, CURLOPT_POST, 1);
	curl_easy_setopt(tvshandle, CURLOPT_ERRORBUFFER, curlerror);
	curl_easy_setopt(tvshandle, CURLOPT_TIMEOUT, TIMEOUT);
//////  //curl_easy_setopt(tvghandle, CURLOPT_FRESH_CONNECT, 1);

	while (days > dagtel) {
		makedate(sys_jaar, sys_maand, sys_dag + dagtel + offset,
			 12, 0, startdatum, tz, 0);
		if (dagtel + offset >= MAXDAYS)
			break;
		fprintf(tempfile, "\n%s\n", startdatum);
		strncpy(datjaar, startdatum, 4);
		datmaand[0] = startdatum[4];
		datmaand[1] = startdatum[5];
		datdag[0] = startdatum[6];
		datdag[1] = startdatum[7];
		sprintf(url,
			//"http://tv-nl.skynet.be/index.html?l1=entertainment&l2=tvguide&l3=programs&l4=channels&channelid=%s&date=%s-%d-%d",
			"http://www.skynet.be/entertainment-nl/tv/kanalen_vtm?channelid=%s&date=%s-%d-%d",
			kanaal->id, datjaar, atoi(datmaand), atoi(datdag));
		if (!stil)
			fprintf(stderr,
				"Ophalen skynet zender %s:\n\t%s\n",
				kanaal->omschrijving, url);
		curl_easy_setopt(tvshandle, CURLOPT_URL, url);
		while (maxconn_sky >= mconnect)
			sleep(1);
		pthread_mutex_lock(&mymutex);
		maxconn_sky++;
		pthread_mutex_unlock(&mymutex);
		position = ftell(tempfile);
		ret = curl_easy_perform(tvshandle);
		for (tel = 0; ret && tel < 3; tel++) {
			fprintf(stderr,
				"Error ophalen %s (skynet) datum %s,...retrying\n",
				kanaal->omschrijving, startdatum);
			ret = curl_easy_perform(tvshandle);
			fseek(tempfile, position, SEEK_SET);
		}
		if (ret) {
			fprintf(stderr,
				"Error MAXRETRY ophalen %s (skynet) datum %s,...abort:\t\n%s\n",
				kanaal->omschrijving, startdatum,
				curlerror);
			fseek(tempfile, position, SEEK_SET);
		}

		dagtel++;
		pthread_mutex_lock(&mymutex);
		maxconn_sky--;
		pthread_mutex_unlock(&mymutex);
/* misschien ooit implementeren....
		curly = 0;
		if(curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &curly) == CURLE_OK )
		{
		//http response is NIET OK, stoppen met verder ophalen
			if( curly != 200 )
				break;
		}
*/
	}

	rewind(tempfile);
	short section = 0;	//indicator voor programma-overzicht

	while (fgets(buffer, 1024, tempfile)) {
		if (buffer[0] == '') {
			strncpy(startdatum, &buffer[1], 8);
			continue;
		}
		if (strstr
		    (buffer,
		     "<ul id=\"programsByDate\" class=\"programs\">")) {
			section = 1;
			continue;
		}
		if (section) {
			if (strstr(buffer, "</ul")) {
				section = 0;
				continue;
			}
		} else
			continue;
		// url voor programma:
		if (p = strstr(buffer, "programkey=")) {
			p = strchr(p, '=');
			if (!p)
				continue;
			p++;
			p1 = strchr(p, '"');
			if (!p1)
				continue;
			*p1 = '\0';
			//p1=strrchr(p, '=');
			//if(!p1 )
			//    continue;
			//p1++;
			// controle op dubbele id's
			if (tel) {
				for (tel2 = 0; tel2 < tel; tel2++) {
					if (!strcmp(p, ids[tel2].id))
						continue;
				}
			}
			ids[tel].id = strdup(p);
			ids[tel].progdatum = strdup(startdatum);
			tel++;
		}
	}
	//for(tel=0;ids[tel].id;tel++) 
	//    fprintf(stderr, "id %s\n", ids[tel].id);
	//for(tel=0;ids[tel].id;tel++) {
	tel = 0;
	avond = 0;
	// grabben per programma:
	while (ids[tel].id) {
		//fprintf(stderr, "id %s\n", ids[tel].id);
		//  \NULL-waarden zetten:
		ids[tel].titel = NULL;
		ids[tel].startuur = NULL;
		ids[tel].startmin = NULL;
		ids[tel].stopuur = NULL;
		ids[tel].stopmin = NULL;
		ids[tel].details = NULL;
		//Waarden resetten voor volgend programma:
		credits = 0;
		videoaspect = 0;
		stars[0] = '\0';
		jaarpremiere[0] = '\0';
		if (genre) {
			free(genre);
			genre = NULL;
		}
		for (tel2 = 0; regie[tel2] != NULL; tel2++) {
			free(regie[tel2]);
			regie[tel2] = NULL;
		}
		for (tel2 = 0; presentator[tel2] != NULL; tel2++) {
			free(presentator[tel2]);
			presentator[tel2] = NULL;
		}
		for (tel2 = 0; actors[tel2] != NULL; tel2++) {
			//fprintf(stderr, "%d %s\n", tel2, actors[tel2]);
			free(actors[tel2]);
			actors[tel2] = NULL;
		}
		// Einde reset
		if (cache) {	//als in cache niet online gaan
			position = vind_cache(ids[tel].id, '3');
			if (position != -1) {
				printcache(position);
				pthread_mutex_lock(&mymutex);
				aantalcache++;
				pthread_mutex_unlock(&mymutex);
				position = -1;
				tel++;
				continue;
			}
		}

		if (tel) {
			if (strcmp
			    (ids[tel - 1].progdatum, ids[tel].progdatum))
				avond = 0;	//indicatie om datum na middernacht te bepalen
		}
		truncate(template, 0);
		rewind(tempfile);
		//`sprintf(url, "http://tv-nl.skynet.be/index.html?l1=actuality&l2=tvguide&l3=programs&l4=detail&programkey=%s\n", ids[tel].id);
		sprintf(url,
			"http://www.skynet.be/entertainment-nl/tv/tv-gids/detail_?programkey=%s\n",
			ids[tel].id);
		//fprintf(stderr, "%s %d http://tv-nl.skynet.be/index.html?l1=actuality&l2=tvguide&l3=programs&l4=detail&programkey=%s\n",kanaal->id,tel, ids[tel].id);
		curl_easy_setopt(tvshandle, CURLOPT_URL, url);
		while (maxconn_sky >= mconnect)
			sleep(1);
		pthread_mutex_lock(&mymutex);
		maxconn_sky++;
		pthread_mutex_unlock(&mymutex);
		ret = curl_easy_perform(tvshandle);
		for (tel2 = 0; ret && tel2 < 3; tel2++) {
			fprintf(stderr,
				"Error ophalen programma-id %s (skynet):...retrying\n",
				ids[tel].id);
			ret = curl_easy_perform(tvshandle);
		}
		if (ret) {
			fprintf(stderr,
				"Error MAXRETRY ophalen programma-id %s (skynet):...abort:\t\n%s\n",
				ids[tel].id, curlerror);
			tel++;
			pthread_mutex_lock(&mymutex);
			maxconn_sky--;
			pthread_mutex_unlock(&mymutex);
			continue;
		}
		pthread_mutex_lock(&mymutex);
		maxconn_sky--;
		pthread_mutex_unlock(&mymutex);
		rewind(tempfile);
		strncpy(datjaar, ids[tel].progdatum, 4);
		datmaand[0] = ids[tel].progdatum[4];
		datmaand[1] = ids[tel].progdatum[5];
		datdag[0] = ids[tel].progdatum[6];
		datdag[1] = ids[tel].progdatum[7];
		while (fgets(buffer, 1024, tempfile)) {
			if (p = strstr(buffer, "box programDetails")) {
				while (fgets(buffer, 1024, tempfile)) {
					if (p = strstr(buffer, "<h2>"))
						break;
				}
				if (!p)
					continue;
				p = strchr(p, '>');
				p++;
				p1 = strchr(p, '<');
				*p1 = '\0';
				ids[tel].titel =
				    malloc((strlen(p) +
					    25) * sizeof(char));
				strcpy(ids[tel].titel, p);
				conv_char(ids[tel].titel);
				ids[tel].details = NULL;
				while (fgets(buffer, 1024, tempfile)) {
					if (strstr
					    (buffer,
					     "<div class=\"info\">")
					    || strstr(buffer,
						      "<p><strong>"))
						break;
					if (p =
					    strstr(buffer,
						   "?channelid=")) {
						p = strstr(buffer, "van ");
						if (!p)
							continue;
						p = strchr(p, ' ');
						p++;
						if (!isdigit(*p))
							continue;
						if ((p1 =
						     strchr(p,
							    ':')) == NULL)
							continue;
						*p1 = '\0';
						ids[tel].startuur =
						    strdup(p);
						if (atoi(ids[tel].startuur)
						    > 10)
							avond = 1;
						p1++;
						p = strchr(p1, ' ');
						*p = '\0';
						ids[tel].startmin =
						    strdup(p1);
						p++;
						p = strchr(p, ' ');
						p++;
						p1 = strchr(p, ':');
						*p1 = '\0';
						ids[tel].stopuur =
						    strdup(p);
						p1++;
						p = strchr(p1, ' ');
						*p = '\0';
						ids[tel].stopmin =
						    strdup(p1);
						continue;
					}
					// programmadetails:
					if ((p = strstr(buffer, "<p>")) &&
					    ids[tel].startuur != NULL) {
						p += 3;
						if (*p == '<')
							continue;
						ids[tel].details =
						    malloc(4096 *
							   sizeof(char));
						ids[tel].details[0] = '\0';
						while (fgets
						       (buffer, 1024,
							tempfile)) {
							if (strstr
							    (buffer,
							     "<div")
							    ||
							    strstr(buffer,
								   "<p><strong>"))
								break;
							if (strstr
							    (buffer,
							     "<p>")) {
								p = strchr
								    (buffer,
								     '>');
								p++;
								if (*p ==
								    '<')
									continue;
								if (p1 =
								    strrchr
								    (p,
								     '<'))
								{
									*p1 = '\n';
									p1++;
									*p1 = '\0';
								}
								if (strlen
								    (p) +
								    strlen
								    (ids
								     [tel].
								     details)
								    >=
								    4090)
									break;
								strcat(ids
								       [tel].
								       details,
								       p);
							}
						}
						groot =
						    strlen(ids[tel].
							   details) - 1;
						while (isspace
						       (ids[tel].
							details[groot])) {
							ids[tel].
							    details[groot]
							    = '\0';
							groot =
							    strlen(ids
								   [tel].
								   details)
							    - 1;
						}
						conv_char(ids[tel].
							  details);
						break;
					}
				}
			}
			if (strstr(buffer, "<div class=\"info\">") ||
			    strstr(buffer, "<p><strong>")) {
				while (1) {
					if (p = strstr(buffer, "</div>")) {
						break;
					}
					//Jaar:
					if (strstr
					    (buffer, "<p><strong>Jaar:")) {
						p = strstr(buffer,
							   "/strong");
						if (!p)
							continue;
						p = strchr(p, '>');
						if (!p)
							continue;
						p++;
						if (isspace(*p))
							p++;
						p1 = strchr(p, '<');
						*p1 = '\0';
						strcpy(jaarpremiere, p);
					}
					//regisseur:
					if (strstr
					    (buffer,
					     "<p><strong>Regisseur:")) {
						p = strstr(buffer,
							   "/strong");
						if (!p)
							continue;
						p = strchr(p, '>');
						if (!p)
							continue;
						p++;
						if (*p == '<')
							continue;
						p1 = strchr(p, '<');
						if (!p1)
							continue;
						*p1 = '\0';
						if (maak_presenters
						    (p, regie))
							credits = 1;
					}
					//Cast:
					if (strstr
					    (buffer, "<p><strong>Cast:")) {
						p = strstr(buffer,
							   "/strong");
						if (!p)
							continue;
						p = strchr(p, '>');
						if (!p)
							continue;
						p++;
						if (*p == '<')
							continue;
						while (isspace(*p))
							p++;
						p1 = strchr(p, '<');
						if (!p1)
							continue;
						*p1 = '\0';
						if (maak_presenters
						    (p, actors))
							credits = 1;
					}
					//Genre:
					if (strstr
					    (buffer,
					     "<p><strong>Genre:")) {
						p = strstr(buffer,
							   "/strong");
						if (!p)
							continue;
						p = strchr(p, '>');
						if (!p)
							continue;
						p++;
						if (*p == '<')
							continue;
						p1 = strchr(p, '<');
						*p1 = '\0';
						genre =
						    malloc((strlen(p) +
							    20) *
							   sizeof(char));
						strcpy(genre, p);
						convert_genre(genre);
					}
					//breedbeeld
					//if( strstr(buffer, "alt=\"16:9\"") )
					//   videoaspect = 1;
					if (!fgets(buffer, 1024, tempfile))
						break;
				}
			}
		}

		if (!ids[tel].titel || !ids[tel].startuur) {
			if (ids[tel].id) {
				free(ids[tel].id);
				ids[tel].id == NULL;
			}
			if (ids[tel].titel) {
				// fprintf(stderr, "* %s\n", ids[tel].titel);
				free(ids[tel].titel);
				ids[tel].titel == NULL;
			}
			if (ids[tel].details) {
				free(ids[tel].details);
				ids[tel].details == NULL;
			}
			if (ids[tel].progdatum) {
				free(ids[tel].progdatum);
				ids[tel].progdatum == NULL;
			}
			if (ids[tel].startuur) {
				free(ids[tel].startuur);
				ids[tel].startuur == NULL;
			}
			if (ids[tel].startmin) {
				free(ids[tel].startmin);
				ids[tel].startmin == NULL;
			}
			if (ids[tel].stopuur) {
				free(ids[tel].stopuur);
				ids[tel].stopuur == NULL;
			}
			if (ids[tel].stopmin) {
				free(ids[tel].stopmin);
				ids[tel].stopmin == NULL;
			}
			tel++;
			continue;
		} else {
			pthread_mutex_lock(&mymutex);
			aantalprog++;
			pthread_mutex_unlock(&mymutex);
		}
		makedate(atoi(datjaar), atoi(datmaand), atoi(datdag),
			 atoi(ids[tel].startuur), atoi(ids[tel].startmin),
			 starttijd, tz, -1);
		if (avond && atoi(ids[tel].stopuur) < 10)
			makedate(atoi(datjaar), atoi(datmaand),
				 atoi(datdag) + 1, atoi(ids[tel].stopuur),
				 atoi(ids[tel].stopmin), stoptijd, tz, -1);
		else
			makedate(atoi(datjaar), atoi(datmaand),
				 atoi(datdag), atoi(ids[tel].stopuur),
				 atoi(ids[tel].stopmin), stoptijd, tz, -1);

		pthread_mutex_lock(&mymutex);
		printf
		    (" <programme start=\"%s +0%d00\" stop=\"%s +0%d00\" channel=\"%s.skynet.be\">\n",
		     starttijd, tz, stoptijd, tz, kanaal->id);
		printf("   <title lang=\"nl\">%s</title>\n",
		       ids[tel].titel);
		if (ids[tel].details && strlen(ids[tel].details) > 0)
			printf("   <desc lang=\"nl\">%s\n   </desc>\n",
			       ids[tel].details);
		if (credits) {
			printf("   <credits>\n");

			for (tel2 = 0; regie[tel2] != NULL; tel2++)
				printf("       <director>%s</director>\n",
				       regie[tel2]);
			for (tel2 = 0; presentator[tel2] != NULL; tel2++)
				printf
				    ("       <presenter>%s</presenter>\n",
				     presentator[tel2]);
			for (tel2 = 0; actors[tel2] != NULL; tel2++)
				printf("       <actor>%s</actor>\n",
				       actors[tel2]);

			printf("   </credits>\n");
		}
		if (genre)
			printf("   <category>%s</category>\n", genre);
		if (strlen(jaarpremiere) == 4)
			fprintf(stdout, "   <date>%s</date>\n",
				jaarpremiere);
		if (imdb) {
			//wachten op usable imdb
			while (imdbdirty && imdb)
				sleep(3);
			if (imdb) {
				tel2 =
				    get_rating(ids[tel].titel, stars,
					       jaarpremiere, NULL, genre);
				if (tel2 <= 0)
					stars[0] = '\0';
				else {
					aantalimdb++;
					printf
					    ("   <star-rating>\n    <value>%s/10</value>\n   </star-rating>\n",
					     stars);
				}
			}
		}
		if (videoaspect)
			printf
			    ("   <video>\n      <aspect>16:9</aspect>\n   </video>\n");

		printf(" </programme>\n");
		if (cache) {
			fseek(cachetmp, 0, SEEK_END);
			fprintf(cachetmp, "3%s-%s", ids[tel].id,
				ids[tel].progdatum);
			fprintf
			    (cachetmp,
			     " <programme start=\"%s +0%d00\" stop=\"%s +0%d00\" channel=\"%s.skynet.be\">\n",
			     starttijd, tz, stoptijd, tz, kanaal->id);
			fprintf(cachetmp,
				"   <title lang=\"nl\">%s</title>\n",
				ids[tel].titel);
			if (ids[tel].details
			    && strlen(ids[tel].details) > 0)
				fprintf(cachetmp,
					"   <desc lang=\"nl\">%s\n   </desc>\n",
					ids[tel].details);
			if (credits) {
				fprintf(cachetmp, "   <credits>\n");

				for (tel2 = 0; regie[tel2] != NULL; tel2++)
					fprintf(cachetmp,
						"       <director>%s</director>\n",
						regie[tel2]);
				for (tel2 = 0; presentator[tel2] != NULL;
				     tel2++)
					fprintf(cachetmp,
						"       <presenter>%s</presenter>\n",
						presentator[tel2]);
				for (tel2 = 0; actors[tel2] != NULL;
				     tel2++)
					fprintf(cachetmp,
						"       <actor>%s</actor>\n",
						actors[tel2]);

				fprintf(cachetmp, "   </credits>\n");
			}
			if (genre)
				fprintf(cachetmp,
					"   <category>%s</category>\n",
					genre);
			if (strlen(jaarpremiere) == 4)
				fprintf(cachetmp, "   <date>%s</date>\n",
					jaarpremiere);
			if (stars[0] != '\0')
				fprintf(cachetmp,
					"   <star-rating>\n    <value>%s/10</value>\n   </star-rating>\n",
					stars);
			if (videoaspect)
				fprintf
				    (cachetmp,
				     "   <video>\n      <aspect>16:9</aspect>\n   </video>\n");

			fprintf(cachetmp, " </programme>\n");
			fprintf(cachetmp, "\n");
		}
		pthread_mutex_unlock(&mymutex);

		//if(ids[tel].id != NULL )
		//   free(ids[tel].id);
		if (ids[tel].titel != NULL)
			free(ids[tel].titel);
		if (ids[tel].details)
			free(ids[tel].details);
		//if(ids[tel].progdatum)
		//    free(ids[tel].progdatum);
		if (ids[tel].startuur)
			free(ids[tel].startuur);
		if (ids[tel].startmin)
			free(ids[tel].startmin);
		if (ids[tel].stopuur)
			free(ids[tel].stopuur);
		if (ids[tel].stopmin)
			free(ids[tel].stopmin);
		tel++;
	}

	curl_easy_cleanup(tvshandle);

	fclose(tempfile);
	unlink(template);
	//fprintf(stderr, "template %s\n", template);

	return (ret);
}
